//
//  WBRefreshView.swift
//  BAweibo
//
//  Created by baggio on 2017/8/31.
//  Copyright © 2017年 baggio. All rights reserved.
//

import UIKit

class WBRefreshView: UIView {
    
    @IBOutlet weak var tipIconView: UIImageView!
    @IBOutlet weak var loadingIconView: UIImageView!//菊花
    @IBOutlet var tipView: UIView! //箭头和后面一句话，作为一个整体
    
    //false 表示初始状态，箭头向下
    var rotateFlag = false {
        didSet {
            rotateTipIcon()
        }
    }
    
    static func refreshView() -> WBRefreshView {
        //用 UINib 加载 xib
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        return nib.instantiate(withOwner: nil, options: nil)[0] as! WBRefreshView
    }
    
    //旋转
    private func rotateTipIcon() {
        if rotateFlag {
            UIView.animate(withDuration: 0.5) {
                //转-540，保证都在右半圈转
                self.tipIconView.transform = CGAffineTransform(rotationAngle: CGFloat(-3 * Double.pi))
            }
        } else {
            UIView.animate(withDuration: 0.5, animations: {
                //恢复
                self.tipIconView.transform = CGAffineTransform.identity
            })
        }
    }
    
    //开启菊花动画
    func startAnimation() {
        tipView.isHidden = true
        
        let key = "transform.rotation"
        if loadingIconView.layer.animation(forKey: key) != nil {
            return
        }
        
        let anim = CABasicAnimation(keyPath: key)
        anim.toValue = 2 * Double.pi
        anim.repeatCount = MAXFLOAT
        anim.isRemovedOnCompletion = false //页面到后台再恢复，动画默认会移除，改成不移除
        loadingIconView.layer.add(anim, forKey: key)
    }
    
    //结束菊花动画
    func stopAnimation() {
        tipView.isHidden = false
        loadingIconView.layer.removeAllAnimations()
    }
    
}
